#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>

static int s_socket = -1;

void initSocket();
void finalSocket();
void* senderThreadMain(void* arg);

int main(int argc, char* argv[])
{
    initSocket();

    int n;
    char buf[1024];
    pthread_t senderThread;
    int ret = pthread_create(&senderThread, NULL, senderThreadMain, NULL);
    if (0 != ret) {
        fprintf(stderr, "senderThread create failed!\n");
    }

    for (;;) {
        memset(buf, 0, sizeof(buf));
        n = recv(s_socket, buf, 1024, 0);
        if (0 < n) {
            printf("\n%s", buf);
            if (buf[0], '\n') {
            	printf("client>");
                fflush(stdout);
            }
        }
        else if (0 == n) {
        	printf("server is closed, exiting!\n");
        	break;
        }
        else {
            printf("client>");
        }
    }

    finalSocket();
    return 0;
}

void initSocket()
{
    s_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (0 > s_socket) {
        printf("create socket failed!\n");
        return;
    }

    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(struct sockaddr_in));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(30000);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");
    int cnt = connect(s_socket, (struct sockaddr*)&addr, sizeof(addr));
    if (0 > cnt) {
        printf("connect failed(%d)!\n", errno);
        return;
    }
}

void finalSocket()
{
    close(s_socket);
}

void* senderThreadMain(void *arg)
{
    char buf[1024];
    int n;
    for (;;) {
        memset(buf, 0, sizeof(buf));

        fprintf(stdout, "client>");
        fflush(stdout);
        fgets(buf, 1024, stdin);
        int readbytes = strlen(buf);
        buf[readbytes-1] = 0;
        readbytes -= 1;

        int ret = send(s_socket, buf, readbytes, 0);
        printf("sending...(byte:%d)!\n", ret);
        if (0 > ret) {
            printf("send failed(%d)!\n", errno);
        }
    }
    return (void*)0;
}
